<?php

namespace app\api\controller;

use addons\epay\library\Service;
use addons\third\model\Third;
use app\common\controller\Api;
use think\Db;

class Inquiry extends Api
{
    protected $noNeedLogin = ['infoList'];
    protected $noNeedRight = '*';
    /**
     * @return void
     * 提现问题添加
     */
    public function  inquiryAdd(){
        $title = $this->request->post('title');
        $info = $this->request->post('info');
        $imgs = $this->request->post('imgs');
        $reward_money = $this->request->post('reward_money');
        if(!$title || !$info || !$imgs){
            $this->error("缺少必传参数");
        }
        $add_data['title'] = $title;
        $add_data['info'] = $info;
        $add_data['reward_money'] = $reward_money;
        $add_data['createtime'] = time();
        $add_data['updatetime'] = time();
        $add_data['imgs'] = $imgs;
        $add_data['uid'] = $this->auth->id?$this->auth->id:0;
        $in_data_id = Db::name("inquiry_problem")->insertGetId($add_data);
        if($in_data_id > 0){
            if($reward_money > 0){
                $user_id=$this->auth->id;

                $problem_id = $in_data_id;
                $type = $this->request->post('type','wechat');
                $method = $this->request->post('method','wap');
                if(!$problem_id || !$reward_money) $this->error("缺少必传参数");
                //订单号
                $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
                //回调链接
                $notifyurl = $this->request->root(true) . '/addons/epay/index/inquiryadd/paytype/' . $type;
                $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

                $info = get_addon_info('third');
                if (!$info || !$info['state']) {
                    $this->error("请在后台安装第三方登录插件");
                }
                Db::name("inquiry_problem")->where("id",$problem_id)->update(['delete_time'=>time()]);
                try {
                    $third = Third::where('platform', 'wechat')
                        ->where('apptype', $method)
                        ->where('user_id', $this->auth->id)
                        ->find();
                    $openid = $third['openid'];
                    $params = [
                        'amount'    => $reward_money,
                        'orderid'   => $out_trade_no,
                        'type'      => $type,
                        'title'     => "支付{$reward_money}元",
                        'notifyurl' => $notifyurl,
                        'returnurl' => $returnurl,
                        'method'    => $method,
                        'openid'    => $openid
                    ];
                   // $response=Service::submitOrder($reward_money, $out_trade_no, $type, "订单支付", $notifyurl, $returnurl,$method,$openid);
                    $response = Service::submitOrder($params);
                    if($response)
                    {
                        $in_data['user_id'] = intval($user_id);
                        $in_data['inquiry_problem_id'] = $problem_id;
                        $in_data['money'] = $reward_money;
                        $in_data['status'] = 2;
                        $in_data['order'] = $out_trade_no;
                        $in_data['paytype'] = $type;
                        $in_data['createtime'] = time();
                        $in_data['updatetime'] = time();
                        $add1 = Db::name("inquiry_user_reward")->insert($in_data);
                        if(!$add1){
                            $this->error("数据有误");
                        }
                    }
                } catch (GatewayException $e) {
                    throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败，请稍后重试");
                }
                $this->success('成功',$response);
            }
            $this->success('成功');
        }else{
            $this->error("失败");
        }
    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 咨询列表
     */
    public function infoList(){
        $where['id'] = array('>',0);
        //$where['delete_time'] = array('EXP','IS NULL');
        $title = $this->request->post('title');
        if($title){
            $where['title'] = array('like',"%".$title."%");
        }
        $infolist = Db::name('inquiry_problem')
            ->where($where)
            ->where(['delete_time'=>null])
            ->order('id desc')
            ->select();
        $user_id=$this->auth->id;
        foreach ($infolist as $k=>$v){
            $u_data = Db::name('user')
                ->where(['id'=>$v['uid']])
                ->find();
            $infolist[$k]['user_name'] = $u_data['nickname'];
            if($user_id){
                $fabulous = Db::name("inquiry_user_fabulous")->where(['user_id'=>$user_id,'inquiry_problem_id'=>$v['id']])->find();
                $collection = Db::name("inquiry_user_collection")->where(['user_id'=>$user_id,'inquiry_problem_id'=>$v['id']])->find();
                if($fabulous){
                    $infolist[$k]['is_fabulous'] = 1;
                }else{
                    $infolist[$k]['is_fabulous'] = 0;
                }
                if($collection){
                    $infolist[$k]['is_collection'] = 1;
                }else{
                    $infolist[$k]['is_collection'] = 0;
                }
            }else{
                $infolist[$k]['is_fabulous'] = 0;
                $infolist[$k]['is_collection'] = 0;
            }
        }
        //echo Db::name('info_article')->getLastSql();
        $this->success('请求成功',$infolist);
    }
    /**
     * @return void
     * 点赞数
     */
    public function fabulous(){
        $user_id=$this->auth->id;
        $problem_id = $this->request->post('problem_id');
        if(!$problem_id) $this->error("缺少必传参数");
        $d = Db::name("inquiry_user_fabulous")->where(['user_id'=>$user_id,'inquiry_problem_id'=>$problem_id])->find();
        if(!$d) {
            $save1 = Db::name("inquiry_problem")->where("id",$problem_id)->setInc("fabulous_sum",1);
            $add_data['user_id'] = $user_id;
            $add_data['inquiry_problem_id'] = $problem_id;
            $add_data['createtime'] = time();
            $add_data['updatetime'] = time();
            $add1 = Db::name("inquiry_user_fabulous")->insert($add_data);
            if($save1 && $add1){
                $this->success('成功');
            }else{
                $this->error("失败");
            }
        }else{
            $save1 = Db::name("inquiry_problem")->where("id",$problem_id)->setDec("fabulous_sum",1);
            $add_data['user_id'] = $user_id;
            $add_data['inquiry_problem_id'] = $problem_id;

            $add1 = Db::name("inquiry_user_fabulous")->where($add_data)->delete();
            if($save1 && $add1){
                $this->success('成功');
            }else{
                $this->error("失败");
            }
        }

    }
    /**
     * @return void
     * 评论数
     */
    public function comment(){
        $user_id=$this->auth->id;
        $problem_id = $this->request->post('problem_id');
        $comment = $this->request->post('comment');
        if(!$problem_id || !$comment) $this->error("缺少必传参数");
        $save1 = Db::name("inquiry_problem")->where("id",$problem_id)->setInc("comment_sum",1);
        $add_data['user_id'] = $user_id;
        $add_data['inquiry_problem_id'] = $problem_id;
        $add_data['comment'] = $comment;
        $add_data['createtime'] = time();
        $add_data['updatetime'] = time();
        $add1 = Db::name("inquiry_user_comment")->insert($add_data);
        if($save1 && $add1){
            $this->success('成功');
        }else{
            $this->error("失败");
        }
    }
    /**
     * @return void
     * 收藏数
     */
    public function collection(){
        $user_id = $this->auth->id;
        $problem_id = $this->request->post('problem_id');
        if(!$problem_id) $this->error("缺少必传参数");
        $d = Db::name("inquiry_user_collection")->where(['user_id'=>$user_id,'inquiry_problem_id'=>$problem_id])->find();
        if(!$d) {
            $save1 = Db::name("inquiry_problem")->where("id",$problem_id)->setInc("collection_sum",1);
            $add_data['user_id'] = $user_id;
            $add_data['inquiry_problem_id'] = $problem_id;
            $add_data['createtime'] = time();
            $add_data['updatetime'] = time();
            $add1 = Db::name("inquiry_user_collection")->insert($add_data);
            if($save1 && $add1){
                $this->success('成功');
            }else{
                $this->error("失败");
            }
        }else{
            $save1 = Db::name("inquiry_problem")->where("id",$problem_id)->setDec("collection_sum",1);
            $add_data['user_id'] = $user_id;
            $add_data['inquiry_problem_id'] = $problem_id;

            $add1 = Db::name("inquiry_user_collection")->where($add_data)->delete();

            if($save1 && $add1){
                $this->success('成功');
            }else{
                $this->error("失败");
            }
        }

    }
    /**
     * @return void
     * 打赏数
     */
    public function reward(){
        $user_id=$this->auth->id;
        $problem_id = $this->request->post('problem_id');
        $reward_money = $this->request->post('reward_money');
        $type = $this->request->post('type','wechat');
        $method = $this->request->post('method','miniapp');
        if(!$problem_id || !$reward_money) $this->error("缺少必传参数");
        /* $save1 = Db::name("info_article")->where("id",$article_id)->setInc("reward_sum",$reward_money);
         $add_data['user_id'] = $user_id;
         $add_data['info_article_id'] = $article_id;
         $add_data['money'] = $reward_money;
         $add_data['createtime'] = time();
         $add_data['updatetime'] = time();
         $add1 = Db::name("info_user_reward")->insert($add_data);
         if($save1 && $add1){
             $this->success('成功');
         }else{
             $this->error("失败");
         }*/
        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/inquiryreward/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $info = get_addon_info('third');
        if (!$info || !$info['state']) {
            $this->error("请在后台安装第三方登录插件");
        }
        try {
            $third = Third::where('platform', 'wechat')
                ->where('apptype', $method)
                ->where('user_id', $this->auth->id)
                ->find();
            $openid = $third['openid'];
            $response=Service::submitOrder($reward_money, $out_trade_no, $type, "订单支付", $notifyurl, $returnurl,$method,$openid);
            //$response = Service::submitOrder($params);
            if($response)
            {
                $add_data['user_id'] = $user_id;
                $add_data['inquiry_problem_id'] = $problem_id;
                $add_data['money'] = $reward_money;
                $add_data['status'] = 2;
                $add_data['order'] = $out_trade_no;
                $add_data['paytype'] = $type;
                $add_data['createtime'] = time();
                $add_data['updatetime'] = time();
                $add1 = Db::name("inquiry_user_reward")->insert($add_data);
                if(!$add1){
                    $this->error("数据有误");
                }
            }
        } catch (GatewayException $e) {
            throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败，请稍后重试");
        }
        //$response['order'] = $out_trade_no;
        $this->success('成功',$response);
    }
    /**
     * @return void
     * 购买
     */
    public function buy(){
        $user_id=$this->auth->id;
        $problem_id = $this->request->post('problem_id');
        $type = $this->request->post('type','wechat');
        $method = $this->request->post('method','miniapp');
        if(!$problem_id) $this->error("缺少必传参数");
        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);
        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/inquirybuy/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $info = get_addon_info('third');
        if (!$info || !$info['state']) {
            $this->error("请在后台安装第三方登录插件");
        }
        $data = Db::name("inquiry_problem")->where('id',$problem_id)->find();
        $money = $data['money'];
        try {
            $third = Third::where('platform', 'wechat')
                ->where('apptype', $method)
                ->where('user_id', $this->auth->id)
                ->find();
            $openid = $third['openid'];
            $response=Service::submitOrder($money, $out_trade_no, $type, "订单支付", $notifyurl, $returnurl,$method,$openid);
            //$response = Service::submitOrder($params);
            if($response)
            {
                $add_data['user_id'] = $user_id;
                $add_data['inquiry_problem_id'] = $problem_id;
                $add_data['money'] = $money;
                $add_data['status'] = 2;
                $add_data['order'] = $out_trade_no;
                $add_data['paytype'] = $type;
                $add_data['createtime'] = time();
                $add_data['updatetime'] = time();
                $add1 = Db::name("inquiry_user_buy")->insert($add_data);
                if(!$add1){
                    $this->error("数据有误");
                }
            }
        } catch (GatewayException $e) {
            throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败，请稍后重试");
        }
        //$response['order'] = $out_trade_no;
        $this->success('成功',$response);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 详情
     */
    public function detail(){
        $problem_id = $this->request->post('problem_id');
        if(!$problem_id) $this->error("缺少必传参数");
        $ar_data = Db::name("inquiry_problem")->where('id',$problem_id)->find();
        if(!$ar_data) $this->error("数据有误");
        $com_data = Db::name("inquiry_user_comment i")
            ->field("i.*,u.username")
            ->join("user u", 'u.id=i.user_id')
            ->where('i.inquiry_problem_id',$problem_id)
            ->select();
        $ar_data['comment'] = $com_data;
        $this->success('成功',$ar_data);
    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 收藏
     */
    public function inquiry_collection(){
        $user_id=$this->auth->id;
        $w['t.user_id'] = $user_id;
        $son_data = Db::name("inquiry_user_collection t") ->join('inquiry_problem ar', 't.inquiry_problem_id=ar.id')->where($w)->field("ar.*")->select();
        $this->success('成功',$son_data);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 我的咨询
     */
    public function inquiry_comment(){
        $user_id=$this->auth->id;
        $w['uid'] = $user_id;
        $son_data = Db::name("inquiry_problem")->where($w)->where(['delete_time'=>null])->select();
        foreach ($son_data as $k=>$v){

            if($user_id){
                $fabulous = Db::name("inquiry_user_fabulous")->where(['user_id'=>$user_id,'inquiry_problem_id'=>$v['id']])->find();
                $collection = Db::name("inquiry_user_collection")->where(['user_id'=>$user_id,'inquiry_problem_id'=>$v['id']])->find();
                if($fabulous){
                    $son_data[$k]['is_fabulous'] = 1;
                }else{
                    $son_data[$k]['is_fabulous'] = 0;
                }
                if($collection){
                    $son_data[$k]['is_collection'] = 1;
                }else{
                    $son_data[$k]['is_collection'] = 0;
                }
            }else{
                $son_data[$k]['is_fabulous'] = 0;
                $son_data[$k]['is_collection'] = 0;
            }
        }
        $this->success('成功',$son_data);
    }
}
